﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace Mr.Http.Controllers
{
    public class UploadController : Controller
    {
        //
        // GET: /Upload/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Upload()
        {
            bool useBinary =
                Boolean.TryParse(this.Request["useBinary"], out useBinary)
                ? useBinary
                : false; //  default false;

            string filePath = "C:/upload/";

            if (this.Request.Files.Count > 0)
            {
                foreach (string filename in this.Request.Files)
                {
                    HttpPostedFileBase file = this.Request.Files[filename];
                    file.Save(filePath + file.FileName, useBinary);
                }
            }
            return this.Json(new { result = "OK", status = "200" });
        }
    }

    public static class FileExtension
    {
        public static void Save(this HttpPostedFileBase file, string fileName, bool useBinary)
        {
            if (!useBinary)
            {
                using (StreamReader reader = new StreamReader(file.InputStream))
                {
                    string fileBase64Str = reader.ReadToEnd();
                    File.WriteAllBytes(fileName, Convert.FromBase64String(fileBase64Str));
                }
            }
            else
            {
                file.SaveAs(fileName);
            }
        }
    }
}
